#include "clockin_machine.h" 
#include "sys_manager.h"
#include <string>
extern string username;

//查找当前日期的前一天；
string GetDatePrevious(int year,int mon,int day,int hour,int min,int sec)
{
     // 1）获取当前日期距离1900年的秒数
    struct tm tmToday = {sec, min, hour, day, mon-1, year-1900, 0 , 0, 0};
    time_t tToday = mktime(&tmToday);   // 获取秒数
      
    //2) 获得前一天的日期；
    time_t tYesterday = tToday - 24*60*60;    // 前一天的秒数
    struct tm* tmYest = localtime(&tYesterday);              

    //printf("%4d-%2d-%2d",tmYest->tm_year + 1900,tmYest->tm_mon+1,tmYest->tm_mday);
    string Year = to_string(tmYest->tm_year);
    string Month = to_string(tmYest->tm_mon+1);
    string Day = to_string(tmYest->tm_mday);
    if(tmYest->tm_mon+1 < 10){
        Month = "0" + Month;
    }
    if(tmYest->tm_mday < 10){
        Day = "0" + Day;
    }
    string tmp = Year + "-" + Month + "-" + Day;
    return tmp;
}

//上班打卡
void punch_in(struct card_info& ci)
{
	// struct card_info ci;
	//ci.staff_id = username;
	struct card_info tmp;  //建立空的结构体接收某一天的打卡信息查询结果
	tmp.staff_id = ci.staff_id; 
	string start_time; //记录上班打卡时间
	start_time = getNow(DATETIME); //获得当前系统时间，格式：Y-m-d H:M:S
	string start_t = start_time.substr(11,  8);
	string clockinTime1(CLOCKIN_TIME1);
	string clockinTime2(CLOCKIN_TIME2);

	//DATETIME转化为int year,int mon,int day,int hour,int min,int sec
	int year = atoi(start_time.substr(0, 4).c_str());
	int mon = atoi(start_time.substr(5, 2).c_str());
	int day = atoi(start_time.substr(8, 2).c_str());
		
	string yestday = GetDatePrevious(year,mon,day,0,0,0);  //格式yyyy-mm-dd

	tmp.today = yestday;
	if(queryCardInfo( tmp)){  //查找前一天的工作时间
		//前一天加班大于3h且在九点之前打卡，或者前一天加班不够3h但在7点之前打卡，都记为打卡成功 
        if(((tmp.work_time - WORKTIME) >= 3*60 && start_t <= CLOCKIN_TIME2) || 
           ((tmp.work_time - WORKTIME) < 3*60 && start_t < CLOCKIN_TIME1))
        {
            printf("Successfully punch_in!\n");
            ci.is_late = 0;  //没有迟到 
        }
        //打卡失败的两种情况 
        else if((tmp.work_time - WORKTIME) < 3*60){ 
			int late_time = -(60*atoi((clockinTime1.substr(0, 2)).c_str()) + atoi((clockinTime1.substr(3, 2)).c_str())) + (60*atoi((start_t.substr(0, 2)).c_str()) + atoi((start_t.substr(3, 2)).c_str()));
            printf("you have late for %d minutes\n", late_time);
			ci.is_late = 1;  //迟到标记 
        }
        else{
			int late_time = -(60*atoi((clockinTime2.substr(0, 2)).c_str()) + atoi((clockinTime2.substr(3, 2)).c_str())) + (60*atoi((start_t.substr(0, 2)).c_str()) + atoi((start_t.substr(3, 2)).c_str()));
            printf("you have late for %d minutes\n", late_time);
			ci.is_late = 1;  //迟到标记 
        }
	}
	else{  //无前一天打卡时间
		if(start_t < CLOCKIN_TIME1){
			printf("Successfully punch_in!\n");
			ci.is_late = 0;  //没有迟到 
		}
		else{
			int late_time = -(60*atoi((clockinTime1.substr(0, 2)).c_str()) + atoi((clockinTime1.substr(3, 2)).c_str())) + (60*atoi((start_t.substr(0, 2)).c_str()) + atoi((start_t.substr(3, 2)).c_str()));
			printf("you have late for %d minutes\n", late_time);
			ci.is_late = 1;  //迟到标记
		}
	}

	//上班时间入库，插入成功返回true
	if(insertPunchInTime(ci.staff_id, start_time)){
		cout<<"打卡时间："<<start_time<<endl;
	}
	else{
		cout<<"系统错误，上班打卡失败！可后期补卡"<<endl;
	}
}

//下班打卡
void punch_out(struct card_info& ci)
{
	// struct card_info ci;
	//extern string username;
	//ci.staff_id = username;
	struct card_info tmp1;
	tmp1.staff_id = ci.staff_id;
	string end_time; //下班打卡时间
	end_time = getNow(DATETIME); //获得当前系统时间，格式：Y-m-d H:M:S
	
	if(isPunchIn(ci.staff_id)){  //判断某员工是否有打上班卡，无上班卡不给打下班卡
		string end_t = end_time.substr(11, 8);
	    cout << "下班打卡时间：" <<  end_t << endl;

		//string today = end_time.substr(0,10); //查询当天上班打卡时间
		if(queryCardInfo(tmp1)){
			string puchin_t = tmp1.punch_in_time.substr(11, 8);
			ci.work_time = (60*atoi((end_t.substr(0, 2)).c_str()) + atoi((end_t.substr(3, 2)).c_str())) - (60*atoi((puchin_t.substr(0, 2)).c_str()) + atoi((puchin_t.substr(3, 2)).c_str()));    //工作时长等于两次打卡的时间间隔 
	    	printf("今日工作时长：%d minutes\n", ci.work_time); 
		}
		else{
			cout<<"系统错误！请联系管理员"<<endl;
		}	 
		   
	    if(ci.work_time < WORKTIME && end_t <= CLOCKIN_TIME3){   //工作时长少于8小时 ，记为早退 
	        printf("you have left early for %d minutes\n", WORKTIME - ci.work_time); 
	        ci.is_leave_early = 1;	                 
	    }
	    else if(ci.work_time >= WORKTIME && end_t <= CLOCKIN_TIME3){  //工作时长大于8小时，打卡时间不晚于晚上12点 
	        printf("Successfully punch_out!\n");
	    } 
	    else{
	    	printf("you have already missed the time for punch_out!\n"); 
	        ci.is_miss = 1;  //超过晚上12点，记为缺卡 
	    }		
	}
    else{
		cout<<"抱歉！你未打上班卡，不能打下班卡！"<<endl;  	 
    	ci.work_time = 0;       //未打上班卡，工作时间按零记，并记为旷工 
    	ci.is_absenteeism = 1;  //旷工标记
	}

	//下班时间入库，插入成功返回true
	if(insertPunchOutTime(ci.staff_id, end_time)){
		cout<<"打卡时间："<<end_time<<endl;
	}
	else{
		cout<<"系统错误，下班打卡失败！可后期补卡"<<endl;
	}
}

//打卡机系统入口
void clockin_machine_start()
{
	struct card_info ci;
	//extern string username;
	ci.staff_id = username;
    cout<<"欢迎来到打卡机系统"<<endl;
    cout<<"1.上班打卡"<<endl;
    cout<<"2.下班打卡"<<endl;
	cout<<"3.退出"<<endl;
    cout << "请输入你的选择：" << endl;
	int choice;
    cin >> choice;
    switch(choice){
        case 1:
            punch_in(ci);
			break;
        case 2:
            punch_out(ci);
			break;
        case 3:
            exit(0);
			break;
        default:printf("\nInvalid input!\n");
    }  

	//其他信息入库
	if(insertDailyCardInfo(ci)){
		cout<<"打卡信息录入成功!"<<endl;
	}
	else{
		//cout<<endl;
		cout<<"打卡信息录入失败!"<<endl;
	} 
}